package com.example.jbmsuppliers.sinopec.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.jbmsuppliers.R;
import com.example.jbmsuppliers.sinopec.net.NetWork;
import com.example.jbmsuppliers.sinopec.utlis.ExitAppUtlis;
import com.example.jbmsuppliers.sinopec.view.DialogLoading;
import com.example.jbmsuppliers.sinopec.view.MyLog;
import com.example.jbmsuppliers.sinopec.view.MyToast;
import com.jbm.jbmsupplier.util.Login;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.example.jbmsuppliers.sinopec.Constant.WX_APP_ID;
import static com.example.jbmsuppliers.sinopec.Constant.WX_CODE;
import static com.example.jbmsuppliers.sinopec.Constant.WX_SECRET;
import static com.jbm.jbmsupplier.util.abstracts.SendMessageInterfase.gSocket;

/**
 * 李征
 * Created by 家帮忙 on 2017/1/10.
 */

public class LoginActivity extends OvertActivity implements View.OnClickListener {
    public static boolean isWXLogin = false;
    public static IWXAPI wxApi;
    @InjectView(R.id.login_weinxin)
    Button loginWeinxin;
    @InjectView(R.id.goback_ps_weixins)
    Button gobackPsWeixin;
    @InjectView(R.id.teloginqtdl)
    Button teloginqtdl;
    @InjectView(R.id.layout)
    LinearLayout layout;


    private DialogLoading dialogLoading;
    public final static int LOGINSUCCESS = 0001;
    public final static int CMD_WXKEYLOGIN = 0002;
    public final static int WXMESSFILL = 0003;
    private final int PHOTOLOGIN = 0004;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editshar;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wx_login);
        ExitAppUtlis.getInstance().addActivity(this);
        ButterKnife.inject(this);
        wxApi = WXAPIFactory.createWXAPI(this, WX_APP_ID, true);
        wxApi.registerApp(WX_APP_ID);
        mSharedPreferences = getSharedPreferences("sinopecall",
                Activity.MODE_PRIVATE);
        editshar = mSharedPreferences.edit();
        teloginqtdl.setOnClickListener(this);

    }

    public void wechatLoding(View v) {
//        NetWork network = new NetWork(handler);
//        network.getWeiXinLogin("ozr1Iw6VSqlTg5YkloEr3mhxOF6A", "");
        if (!wxApi.isWXAppInstalled()) {
            MyToast.show(this, "请先安装微信应用", Toast.LENGTH_SHORT);
        } else if (!wxApi.isWXAppSupportAPI()) {
            MyToast.show(this, "请先更新微信应用", Toast.LENGTH_SHORT);
        } else {
            DialogLoading dialogLoading=new DialogLoading(this,"加载中...");
            dialogLoading.show();
            // 将该app注册到微信
            isWXLogin = true;
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo";
            wxApi.sendReq(req);
            setregis();

        }
    }
public void setregis(){
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(isWXLogin){
                if (dialogLoading!=null){
                    dialogLoading.dismiss();
                }
            }
        }
    },new IntentFilter("IS_WEIXIMN"));
}
    @Override
    protected void onResume() {
        super.onResume();
        if (isWXLogin) {
            dialogLoading = new DialogLoading(this, "加载中...", true);
            dialogLoading.show();
            LoadWEIXINInfo();
        }
    }

    private void LoadWEIXINInfo() {
        if (!WX_CODE.equals("")) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APP_ID + "&secret=" + WX_SECRET + "&code=" + WX_CODE + "&grant_type=authorization_code";
                    OkHttpUtils.get().url(accessTokenUrl).build().execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e) {
                            //请求网络错误信息s
                            MyLog.e("微信请求openid错误信息", e + "");
                        }

                        @Override
                        public void onResponse(String response) {
                            if (response != null) {
                                try {
                                    JSONObject json = new JSONObject(response);
                                    String accessToken = json.getString("access_token");
                                    String openId = json.getString("openid");
                                    if (accessToken != null) {
                                        String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
                                                + accessToken + "&openid=" + openId;
                                        OkHttpUtils.get().url(userUrl).build().execute(new StringCallback() {
                                            @Override
                                            public void onError(Call call, Exception e) {
                                                //请求网络错误信息
                                                MyLog.e("微信请求用户信息的错误", e + "");
                                            }

                                            @Override
                                            public void onResponse(String response) {
                                                JSONObject json = null;
                                                try {
                                                    json = new JSONObject(response);
                                                    handler.sendMessage(handler.obtainMessage(LOGINSUCCESS, json));
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                    if (dialogLoading != null) {
                                                        dialogLoading.dismiss();
                                                    }
                                                }


                                            }
                                        });
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    if (dialogLoading != null) {
                                        dialogLoading.dismiss();
                                    }
                                }
                            } else {
                                if (dialogLoading != null) {
                                    dialogLoading.dismiss();
                                }
                                //登录超时


                            }


                        }
                    });


                }
            }).start();


        }
        isWXLogin = false;

    }

    //获取到微信用户的信息进行登录
    private void weixinLoginLoading(HashMap<String, String> weixinhas) {
        NetWork network = new NetWork(handler);
        network.getWeiXinLogin(weixinhas.get("phname"), "");
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGINSUCCESS: {
                    JSONObject request = (JSONObject) msg.obj;
                    try {
                        String userName = request.getString("unionid");//id
                        String nickname = request.getString("nickname");//昵称
                        String headumgur = request.getString("headimgurl");//图片
                        int sex = request.getInt("sex");
                        if (!userName.equals("")) {
                            if (!nickname.equals("")) {
                                if (!headumgur.equals("")) {
                                    HashMap<String, String> has = new HashMap<>();
                                    has.put("phname", userName);
                                    editshar.putString("phname", userName)//登录id
                                            .putString("username", nickname)//昵称
                                            .putString("headumgur", headumgur)//图片
                                            .putString("weinxinlogin", "weixin")
                                            .putInt("sex", sex)
                                            .commit();
                                    weixinLoginLoading(has);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                }
                case CMD_WXKEYLOGIN: {
                    String resul = (String) msg.obj;
                    if (resul != null) {
                        if (resul.equals("Login OK")) {
                            if (gSocket.nickname.equals("") && gSocket.logo.equals("")) {
                                String nickname = mSharedPreferences.getString("username", "");
                                int sex = mSharedPreferences.getInt("sex", 0);
                                String headimgurl = mSharedPreferences.getString("headumgur", "");
                                NetWork network = new NetWork(handler);
                                network.getFill(gSocket.login_id, nickname, sex, headimgurl);
                            }
                            if (dialogLoading != null) {
                                dialogLoading.dismiss();
                            }
                            editshar.putBoolean("IsLogin", true).commit();
                            sendBroadcast(new Intent("isBack").putExtra("login",true).putExtra("relogin","login1"));//
                            //成功
                            MainActivity.goNewHome();
                            finish();
                        } else if (resul.equals("FAILED")) {
                            if (dialogLoading != null)
                                dialogLoading.dismiss();
                            hint("登录失败请检查网络");
                            //登录超时

                        } else {
                            //没有注册的用户
                            if (dialogLoading != null) {
                                dialogLoading.dismiss();
                            }
                            finish();
                            startActivity(new Intent(LoginActivity.this, RegisterActivity.class));

                        }
                    }


                    break;
                }
                case PHOTOLOGIN: {
                    getPhotoLogin();
                    break;
                }
                case WXMESSFILL: {
                    Login result = (Login) msg.obj;
                    if (result.equals("time out"))
                        MyLog.e(result.errorinfo);
                    else
                        MyLog.e(result.errorinfo);
                    break;
                }

            }
        }
    };

    private void getPhotoLogin() {//其他登录
        startActivity(new Intent(this, PhotoLoginActivity.class));
        finish();
    }

    @OnClick({R.id.goback_ps_weixins, R.id.teloginqtdl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.goback_ps_weixins:
                finish();
                if (mSharedPreferences.getBoolean("IsLogin",false)!=true){
                  MainActivity.goNewHome();
                }else {
                        finish();}
                break;
            case R.id.teloginqtdl:
                handler.sendMessage(handler.obtainMessage(PHOTOLOGIN));
                break;
        }
    }

}
